package view.activity
{
	import base.components.FileUpload;
	
	import business.EventDelegate;
	
	import events.MyLogEvent;
	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.VBox;
	import mx.containers.ViewStack;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.CheckBox;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.controls.DateField;
	import mx.controls.Image;
	import mx.controls.LinkButton;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.core.IFlexDisplayObject;
	import mx.events.CloseEvent;
	import mx.events.DropdownEvent;
	import mx.managers.PopUpManager;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;
	
	[Bindable]
	public class ActivityClass extends VBox
	{
		public var searchModes:ArrayCollection = new ArrayCollection(
			[ {label:"活动ID", data:0},
				{label:"活动名称", data:1}, 
				{label:"活动时间", data:2},
				{label:"游戏ID", data:3},
			]);
		
		public var stitle:TextInput;
		public var prize:TextInput;
		public var activityId:TextInput;
		public var activityTitle:TextInput;
		public var activityStartTime:DateField;
		public var activityEndTime:DateField;
		public var activityReGame:TextInput;
		public var activityCopartners:TextInput;
		public var activityDetail:TextArea;
		public var activitySummary:TextArea;
		public var searchInputStack:ViewStack;
		public var item_search_input:TextInput;
		public var item_search_input_time:DateField;
		//public var act_in:RadioButton;
		//public var act_out:RadioButton;
		//        public var isSpecial:CheckBox;
		public var isFromEvent:CheckBox;
		public var specialURL:TextInput;
		public var specialPicURL:TextInput;
		public var ActivityGrid:DataGrid;
		public var bigPic:Image;
		public var smallPic:Image;
		public var smallPicURL:TextInput;
		public var sPic:Image;
		public var sPicURL:TextInput;
		public var bigMakerBtn:Button;
		
		public var page:int;
		public var tips:String
		public var pageIndices:Array;
		public var pagecnt:int;
		public var activeType:String;
		
		private var delegateActivity:EventDelegate;
		private var _m_items:ArrayCollection;
		private var display:IFlexDisplayObject;
		private var logId:String = '-1'; 	
		
		public function ActivityClass()
		{
			super();
			delegateActivity = new EventDelegate(this);
			
			this.addEventListener("dataReflesh",makePageIndices);
			
		}
		
		public function onDataGridItemClick(event:Event):void
		{
			bigMakerBtn.enabled = true;
		}
		
		public function get m_items():ArrayCollection
		{
			return this._m_items;
		}		
		
		public function set m_items(value:ArrayCollection):void
		{
			_m_items = value;
			dispatchEvent(new Event('dataReflesh'));
		}
		
		public function onRefreshClick():void
		{
			//getDate();
			getPage(page);
		}
		
		/* public function actChangeEvent(event:Event):void
		{
		var outFlag:Boolean = false;
		if(event.target.id == 'act_out')
		{
		outFlag = true;
		}
		getPage(0,outFlag);
		} */
		
		private function getDate():void
		{
			this.delegateActivity.getAllEvents();
		}
		
		public function getAllEventsResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		private function refreshPage(result:Object):void
		{
			result = result.result;
			
			//this.page = result.page>0?result.page:0;
			//this.pagecnt = result.pagecnt>1?result.pagecnt:1;
			
			//this.makePageIndices();
			if(result.code == 0)
			{
				this.itemsPrepare(result.data);
			}
			else
			{
				Alert(result.msg);
			}	
		}
		
		public function itemsPrepare(items:Array,method:String = "get"):void
		{
			//预处理结果集
			for each ( var myitem:Object in items )
			{
				var startTime:Date = new Date();
				startTime.setTime(Number(myitem.startTime)*1000);
				myitem.startTime = startTime;
				
				var endTime:Date = new Date();
				endTime.setTime(Number(myitem.endTime)*1000);
				myitem.endTime = endTime;
				
				myitem.isSpecial = myitem.isSpecial=='1'?true:false;	
				myitem.isFromEvent = myitem.isFromEvent=='1'?true:false;
				
				var nowTime:Date = new Date();	
				if(nowTime.getTime() > startTime.getTime() && nowTime.getTime() < endTime.getTime())
				{
					myitem.expired = '<font color="#FF000">活动中</font>';
				}
				else if(nowTime.getTime() > endTime.getTime())
				{
					myitem.expired = '<font color="#7F8989">已过期</font>';
				}
				else if(nowTime.getTime() < startTime.getTime())
				{
					myitem.expired = '<font color="#FF0000">计划中</font>';
				}
			}
			
			if(method == 'get')
			{
				this.m_items = new ArrayCollection(items);
			}
		}
		
		public function onSearch(type:int):void
		{
			var searchObj:Object = new Object();
			if(type == 0)
			{
				//id
				if(!item_search_input.text)
				{
					tips = '<font color="#FF0000">请输入要查找的活动ID</font>';
					return ;
				}
				searchObj.id = int(item_search_input.text);
			}	
			else if(type == 1)
			{
				//title
				if(!item_search_input.text)
				{
					tips = '<font color="#FF0000">请输入要查找的活动名称</font>';
					return ;
				}				
				searchObj.title = String(item_search_input.text);
			}
			else if(type == 2)
			{
				//time
				if(!item_search_input_time.selectedDate)
				{
					tips = '<font color="#FF0000">请输入要查找的活动时间</font>';
					return ;				
				}
				searchObj.time = (item_search_input_time.selectedDate as Date).getTime()/1000;
			}
			else if(type == 3)
			{
				//gameId
				if(!item_search_input.text)
				{
					tips = '<font color="#FF0000">请输入要查找的关联游戏ID</font>';
					return ;				
				}
				searchObj.gameId = String(item_search_input.text);
			}
			this.delegateActivity.search(searchObj);
		}
		
		public function searchResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				var backData:Array = result.data as Array;
				for each(var data:Object in backData)
				{
					formatData(data);
				}
				this.m_items = new ArrayCollection(backData);
				
			}
			else
			{
				tips = '<font color="#FF0000">活动查找失败</font>';
				Alert.show(result.msg);				
			}
		}
		
		private function formatData(obj:Object):void
		{
			var startTime:Date = new Date();
			startTime.setTime(Number(obj.startTime)*1000);
			obj.startTime = startTime;			
			
			var endTime:Date = new Date();
			endTime.setTime(Number(obj.endTime)*1000);
			obj.endTime = endTime;
			
			obj.isSpecial = obj.isSpecial=='1'?true:false;	
			obj.isFromEvent = obj.isFromEvent=='1'?true:false;		
			
			var nowTime:Date = new Date();	
			if(nowTime.getTime() > startTime.getTime() && nowTime.getTime() < endTime.getTime())
			{
				obj.expired = '<font color="#FF000">活动中</font>';
			}
			else if(nowTime.getTime() > endTime.getTime())
			{
				obj.expired = '<font color="#7F8989">已过期</font>';
			}
			else if(nowTime.getTime() < startTime.getTime())
			{
				obj.expired = '<font color="#FF0000">计划中</font>';
			}					
			
		}
		
		public function addEventHandle(event:Event):void
		{
			var addObj:Object = new Object();
			addObj.title = String(activityTitle.text);
			addObj.detail = String(activityDetail.text);
			addObj.gameId = String(activityReGame.text);
			addObj.copartners = String(activityCopartners.text);
			addObj.summary = String(activitySummary.text);
			addObj.startTime = (activityStartTime.selectedDate as Date).getTime()/1000;
			addObj.endTime = (activityEndTime.selectedDate as Date).getTime()/1000;
			addObj.stitle = String(stitle.text);
			addObj.prize = String(stitle.text);
			if(activeType==null || activeType==''){
				Alert.show("请选择活动类型");
				return;
			}
			addObj.type = activeType;
			addObj.specialURL = String(specialURL.text);
			addObj.specialPicURL = specialPicURL.text;		
			addObj.smallPicURL = smallPicURL.text;	
			addObj.sPicURL = sPicURL.text;
			
			LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goAddEvent);
			LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ACTIVITY, LogUtil.ADD, addObj);			
			//this.delegateActivity.addEvent(addObj);
		}
		
		private function goAddEvent(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goAddEvent);
			this.logId = event.logId;
			delegateActivity.addEvent(event.record);			
		}
		
		public function addEventResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				tips = '<font color="#FF000">新活动(id='+result.id+')添加成功</font>';
				LogUtil.getInstance().setOptSuccessd(this.logId);
			}
			else
			{
				tips = '<font color="#FF0000">活动添加失败</font>';
				Alert.show(result.msg);
			}
		}
		
		public function updateResult(result:Object, token:Object = null):void	
		{
			result = result.result;
			if(result.code == 0)
			{
				refleshDisplayingData(result.data);
				tips = '<font color="#FF000">活动修改成功</font>';
				LogUtil.getInstance().setOptSuccessd(logId);				
			}
			else
			{
				tips = '<font color="#FF0000">活动修改失败</font>';
				Alert.show(result.msg);
			}
		}
		
		public function checkType(i:int):Boolean
		{
			var isThisType:Boolean = false;
			//TODO
			if(ActivityGrid==null)return isThisType;
			var isSpl:String = this.ActivityGrid.selectedItem.isSpecial;
			var isFrEvt:String = this.ActivityGrid.selectedItem.isFromEvent;
			switch(i)
			{
				case 1:
					if(isSpl!='')
					{
						isThisType = isSpl==true;
					}
					break;
				case 2:
					if(isFrEvt!='')
					{
						isThisType = isFrEvt==true;	
					}
					break;
				case 3:
					isThisType =  '3' == this.ActivityGrid.selectedItem.type;
					break;
				case 4:
					isThisType =  '4' == this.ActivityGrid.selectedItem.type;
					break;
			}
			trace("isThisType" + isThisType);
			
			return isThisType;
		}
		
		public function refleshDisplayingData(data:*,method:String='get'):void
		{
			var itemIndex:int;
			for each(var item:Object in m_items)
			{
				if(method == 'get')
				{
					if(item.id == activityId.text)
					{
						var startTime:Date = new Date();
						startTime.setTime(Number(data.startTime)*1000);
						data.startTime = startTime;
						
						var endTime:Date = new Date();
						endTime.setTime(Number(data.endTime)*1000);
						data.endTime = endTime;
						
						
						data.isSpecial = data.isSpecial=='1'?true:false;	
						data.isFromEvent = data.isFromEvent=='1'?true:false;
						
						var nowTime:Date = new Date();	
						if(nowTime.getTime() > startTime.getTime() && nowTime.getTime() < endTime.getTime())
						{
							data.expired = '<font color="#FF000">活动中</font>';
						}
						else if(nowTime.getTime() > endTime.getTime())
						{
							data.expired = '<font color="#7F8989">已过期</font>';
						}
						else if(nowTime.getTime() < startTime.getTime())
						{
							data.expired = '<font color="#FF0000">计划中</font>';
						}													
						
						itemIndex = m_items.getItemIndex(item);
						m_items.removeItemAt(itemIndex);
						m_items.addItemAt(data, itemIndex);
						
						ActivityGrid.selectedItem = data;
					}
				}
			}
			
			if(method == 'del')
			{
				if(data == activityId.text)
				{
					var delItem:Object;
					for each(var item1:Object in m_items)
					{
						if(data == item1.id)
						{
							delItem = item1;
						}	
					}
					itemIndex = m_items.getItemIndex(delItem);
					m_items.removeItemAt(itemIndex);						
				}
			}
			
		}
		
		private function getUpdateItem():Object
		{
			var updateObj:Object = new Object();
			updateObj.id = int(activityId.text);
			updateObj.title = String(activityTitle.text);
			updateObj.detail = String(activityDetail.text);
			updateObj.gameId = String(activityReGame.text);
			updateObj.copartners = String(activityCopartners.text);
			updateObj.summary = String(activitySummary.text);
			updateObj.startTime = (activityStartTime.selectedDate as Date).getTime()/1000;
			updateObj.endTime = (activityEndTime.selectedDate as Date).getTime()/1000;	
			updateObj.stitle = String(stitle.text);
			updateObj.prize = String(prize.text);
			
			if("1" == activeType)
			{
				updateObj.isSpecial = true;
				updateObj.isFromEvent = false;
			}
			else if("2" == activeType)
			{
				updateObj.isSpecial = false;
				updateObj.isFromEvent = true;
			}
			updateObj.type = activeType;
			updateObj.specialURL = specialURL.text;
			updateObj.specialPicURL = specialPicURL.text;	
			updateObj.smallPicURL = smallPicURL.text;		
			updateObj.sPicURL = sPicURL.text;
			
			return updateObj;
		}
		
		public function updateEventHandle(event:Event):void
		{
			if(activityId.text.length <= 0)
			{
				tips = 	tips = '<font color="#FF0000">请选择要修改的选项！</font>';
				return ;
			}
			
			var updateObj:Object = getUpdateItem();
			
			LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goUpdate);
			LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ACTIVITY, LogUtil.UPDATE, updateObj);			
			
			//this.delegateActivity.update(updateObj);
		}
		
		private function goUpdate(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goUpdate);
			this.logId = event.logId;
			delegateActivity.update(event.record);			
		}
		
		public function delEventHandle(event:Event):void
		{
			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;
			
			Alert.show('确定删除这项活动吗？',
				'提示',Alert.YES | Alert.NO,null,onDelConfirmed,null,Alert.NO);
		}
		
		private function onDelConfirmed(event:CloseEvent):void
		{
			if (event.detail==Alert.YES)
			{
				//this.delegateActivity.delEventById(int(activityId.text));
				LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goDelEventById);
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ACTIVITY, LogUtil.DEL, activityId.text);				
			}			
		}
		
		private function goDelEventById(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goDelEventById);
			this.logId = event.logId;
			delegateActivity.delEventById(event.record);			
		}
		
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
		public function delEventByIdResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				refleshDisplayingData(result.id,'del');
				tips = '<font color="#FF000">活动删除成功</font>';	
				LogUtil.getInstance().setOptSuccessd(logId);					
			}
			else
			{
				tips = '<font color="#FF0000">活动删除失败</font>';
				Alert.show(result.msg);				
			}
		}
		
		public function closeEventHandle(event:DropdownEvent):void
		{
			if(ComboBox(event.target).selectedItem.data == 2)
			{
				searchInputStack.selectedIndex = 1
			}
			else
			{
				searchInputStack.selectedIndex = 0;
			}
		}
		
		public function goto(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.page;
			getPage(page);
		}
		
		public function getPage(page:int=0, row:int=10, sort:String='id'):void
		{
			this.delegateActivity.getEvent(page, row, sort);	
		}
		
		public function gotoPage(page:String):void
		{
			if (page.length>0)
			{
				getPage(int(page)-1);
			}
		}
		
		/* public function getIsExpire():Boolean
		{
		var isExpired:Boolean;
		if(act_in.selected)
		{
		isExpired = false;
		}
		else if(act_out.selected == true)
		{
		isExpired = true;
		}
		
		return  isExpired;		
		} */
		
		private function makePageIndices(event:Event=null):void
		{
			var a:Array = new Array();
			a.push({page:0,desc:'首页'});			
			a.push({page:page-1,desc:'前一页'});			
			a.push({page:page+1,desc:'后一页'});
			a.push({page:pagecnt-1,desc:'尾页'});
			this.pageIndices = a;
		}
		
		public function getEventResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if(result.code == 0)
			{
				this.page = result.page>0?result.page:0;
				this.pagecnt = result.pagecnt>1?result.pagecnt:1;				
				var backData:Array = result.data as Array;
				for each(var data:Object in backData)
				{
					formatData(data);
				}
				this.m_items = new ArrayCollection(backData);				
			}
			else
			{
				tips = '<font color="#FF0000">获取资源失败失败</font>';
				Alert.show(result.msg);					
			}
			
		}
		
		public function upload(evt:MouseEvent, type:String):void
		{
			if(activityId.text.length <= 0)
			{
				tips = '<font color="#FF0000">请先选活动，再设置图片</font>';
				return ;
			}
			
			display = PopUpManager.createPopUp(this,FileUpload,true);
			PopUpManager.bringToFront(display);
			PopUpManager.centerPopUp(display);
			
			FileUpload(display).uploadUrl = 'http://www.aipai.com/app/admin/service/upload/uploadgamethumb.php';
			FileUpload(display).variables.eventId = activityId.text;
			FileUpload(display).variables.type = type;
			
			FileUpload(display).addEventListener('uploadComplete',uploadComplete);
			FileUpload(display).addEventListener('uploadDataComplete',onUploadDataComplete);
			FileUpload(display).addEventListener('uploadIOError',function(evt:Event):void{Alert.show('IO错误!', '提示')});
			FileUpload(display).addEventListener('uploadSecurityError',function(evt:Event):void{Alert.show('安全错误!', '提示')});
		}
		
		private function uploadComplete(event:Event):void
		{
			PopUpManager.removePopUp(this.display);	
		}	
		
		private function onUploadDataComplete(event:DataEvent):void
		{
			var result:XML = new XML(event.data);
			
			//this.imgUploadName = result.file_name;
			if(String(result.file_name_www).indexOf('big') >= 0)
			{
				bigPic.source = result.file_name_www+"?sss="+Math.random().toString();
				bigPic.load();
				specialPicURL.text = result.file_name_www;
			}
			else if(String(result.file_name_www).indexOf('small') >= 0)
			{
				smallPic.source = result.file_name_www+"?sss="+Math.random().toString();
				smallPic.load();	
				smallPicURL.text = 	result.file_name_www;
			}
			else if(String(result.file_name_www).indexOf('pic2') >= 0)
			{
				sPic.source = result.file_name_www+"?sss="+Math.random().toString();
				sPic.load();
				sPicURL.text = result.file_name_www;
			}
		}
		
		public function clearPic(event:MouseEvent, type:String):void
		{
			if(type == 'big')
			{
				bigPic.source = null;
				bigPic.load();
				specialPicURL.text = '';
			}
			else if(type == 'small')
			{
				smallPic.source = null;
				smallPic.load();
				smallPicURL.text = '';
			}
			else if( type == "pic2")
			{
				sPic.source = null;	
				sPic.load();
				sPicURL.text = '';
			}
				
			
		}
		
		public function linkto(evt:MouseEvent):void
		{
			navigateToURL(new URLRequest(Image(evt.currentTarget).source.toString()),"_blank");
		}
		
		public var cbIsShow:CheckBox;
		public function onCbIsShowChange(e:Event):void
		{
			if(null != ActivityGrid.selectedItem)
				delegateActivity.sentIsShow(this.ActivityGrid.selectedItem.id, cbIsShow.selected);
		}
		
		public function sentIsShowResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				
			}
			else
			{
				Alert.show(result.msg);
			}
		}
		
		public function addBigMaker():void
		{
			if(ActivityGrid.selectedItem)
				delegateActivity.addBigMaker(getUpdateItem());
		}
		
		public function addBigMakerResult(result:Object, token:Object = null):void
		{
			bigMakerBtn.enabled = false;
		}
		
		
		
	}
}